<?php


namespace App\Services\WebSocket\SocketIo;


use App\Services\WebSocket\Parser;
use App\Services\WebSocket\SocketIo\Packet;
use App\Services\WebSocket\SocketIO\Strategies\HeartbeatStrategy;
use Illuminate\Support\Facades\Log;

class SocketIOParser extends Parser
{

    protected $strategies =[
        HeartbeatStrategy::class
    ];


    public function decode($frame)
    {
        $payload= Packet::getPayload($frame->data);
        return [
            'event' => $payload['event'] ?? null,
            'data' => $payload['data'] ?? null,
        ];
    }
    /**
     * Encode output payload for websocket push.
     *
     * @param string $event
     * @param mixed $data
     *
     * @return mixed
     */
    public function encode(string $event, $data)
    {
        // TODO: Implement encode() method.
        $packet = Packet::MESSAGE.Packet::EVENT;
        $shouldEncode = is_array($data) || is_object($data);
        $data = $shouldEncode ? json_encode($data) : $data;
        $format = $shouldEncode ? '["%s",%s]' :'["%s","%s"]';
        Log::info(['encode' =>$packet . sprintf($format,$event,$data)]);
        return $packet . sprintf($format,$event,$data);
    }
}
